import 'package:flutter/material.dart';

class Canvas2 extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return Canvas2State();
  }
}

class Canvas2State extends State<Canvas2> {
  int type = 0;
  ProgressPainter painter;

  Canvas2State();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    this.type = 0;
    painter = ProgressPainter(type);
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new Scaffold(
      appBar: AppBar(
        title: Text("Canvas2"),
      ),
      body: Column(
        children: <Widget>[
          CustomPaint(
//        child: Text("Canvas2"),
            size: Size(300, 300),
            painter: BgPainter(),
            foregroundPainter: ProgressPainter(type),
          ),
          MyText(type)
        ],
      ),
      floatingActionButton:
          FloatingActionButton(onPressed: onPressFun, child: Text("变色")),
    );
  }

  void onPressFun() {
//    painter.setType(this.type);
    this.type = 1;
    setState(() {});
  }
}

class MyText extends StatelessWidget {
  int type = 0;

  MyText(this.type, {Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Text(type == 0 ? "0" : "1");
  }
}

class BgPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
//    print("BgPainter " + size.toString());
    final ringPaint = Paint()
      ..style = PaintingStyle.fill
      ..color = Color.fromARGB(100, 0, 255, 0);
    canvas.drawRect(Rect.fromLTRB(0, 0, size.width, size.height), ringPaint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    // TODO: implement shouldRepaint
    return null;
  }
}

class ProgressPainter extends CustomPainter {
  int type = 0;

  ProgressPainter(this.type, {Key key}) : super();

  @override
  void paint(Canvas canvas, Size size) {
    print("ProgressPainter " + size.toString() + " type " + type.toString());
    Color clolr = type == 1 ? Colors.redAccent : Colors.blue;
    final Offset offsetCenter = Offset(size.width / 2, size.height / 2);
    double drawRadius = 80;
    final ringPaint2 = Paint()
      ..style = PaintingStyle.stroke
      ..color = clolr
      ..strokeWidth = 20;
    canvas.drawCircle(offsetCenter, drawRadius, ringPaint2);
  }

  @override
  bool shouldRepaint(ProgressPainter oldDelegate) {
    return this.type != oldDelegate.type;
  }

  void setType(int type) {
    this.type = type;
    print("setType " + type.toString());
  }
}
